﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIManager : MonoBehaviour
{
    public static UIManager instance;
    public List<BasePanel> panelList;
    [HideInInspector]
    public UIData uiData = new UIData();
    private Dictionary<string, BasePanel> panelsDictionary;
    private Stack<BasePanel> panelStack;

    // Start is called before the first frame update
    void Awake()
    {
        instance = this;
        init();
        ShowPanel("Panel2");
    }

    // Update is called once per frame
    void Update()
    {

    }

    public void init()
    {
        panelsDictionary = new Dictionary<string, BasePanel>();
        panelStack = new Stack<BasePanel>();

        ConvertPanelListToDictionary(ref panelList, ref panelsDictionary);
        ProhitAllPanel();
    }

    //查找面板
    public BasePanel FindPanel(string panelName) {
        return panelsDictionary.GetValue(panelName);
    }

    //显示面板
    public void ShowPanel(string panelName) {
        BasePanel panel = panelsDictionary.GetValue(panelName);

        if (panel == null) {
            Debug.LogWarning("UIManager.ShowPanel:不存着 "+panelName+" 这个名字的panel");
            return;
        }

        //如果栈不为空，则隐藏当前的panel
        if (panelStack.Count != 0) {
            panelStack.Peek().OnPause();
        }
        panelStack.Push(panel);
        panel.OnEnter();
    }

    //隐藏当前面板
    public void HideCurrentPanel() {
        if (panelStack.Count == 0) { Debug.Log("UIManager.HideCurrentPanel: 当前为空栈"); return;  };
        panelStack.Pop().OnExit();
        panelStack.Peek().OnResume();
    }

    //隐藏所有的面板
    public void ProhitAllPanel() {
        panelStack = new Stack<BasePanel>();

        for (int i = 0; i < panelList.Count; i++) {
            panelList[i].Hide();
        }
    }

    //将panels中的面板保存到字典中
    private void ConvertPanelListToDictionary(ref List<BasePanel> list, ref Dictionary<string, BasePanel> dictionary) {
        //UIPanel列表长度小于零则显示一个警告
        if (list.Count <= 0) {
            Debug.LogWarning("UIpanels List为空，给UImanager添加面板");
            return;
        }

        for (int i = 0; i < list.Count; i++) {
            list[i].uiManager = this;
            list[i].panelName = list[i].gameObject.name;
            list[i].uiData = this.uiData;
            list[i].init();
            dictionary.Add(list[i].panelName, list[i]);
        }
    }
}
